package com.biejiaogroup.librarymanager.controller;

import com.biejiaogroup.librarymanager.entity.Book;
import com.biejiaogroup.librarymanager.entity.User;
import com.biejiaogroup.librarymanager.service.BookService;
import com.biejiaogroup.librarymanager.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Vector;

/**
 * @Author: JesseChan
 * @Date: 2022/5/5
 */
@WebServlet("/queryBook")
public class BookServlet extends HttpServlet
{
    private BookService bookService = new BookService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("utf-8");
        Vector<Book> v = bookService.getAll();
        request.getSession().removeAttribute("books");
        request.getSession().setAttribute("books", v);
        request.getRequestDispatcher("bookManager.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("utf-8");

        String url = request.getHeader("Referer");
        //获取请求的jsp
        String jsp = url.substring(url.lastIndexOf("/") + 1);

        String bookName = request.getParameter("bookName");
        if(StringUtil.isEmpty(bookName)) doGet(request, response);
        else
        {
            System.out.println(jsp);
            System.out.println(bookName);
            Vector<Book> v = bookService.queryBookByName(bookName);
            System.out.println(v.size());
            request.getSession().removeAttribute("books");
            request.getSession().setAttribute("books", v);
            User u = (User) request.getSession().getAttribute("user");
            if(u.getUserLevel() == 0) request.getRequestDispatcher("bookManager.jsp").forward(request, response);
            else request.getRequestDispatcher("mainPage.jsp").forward(request, response);
        }
    }
}
